<template>
  <div class="chat-input" :class="{ disabled: isDisabled }">
    <textarea
      v-model="message"
      :placeholder="isDisabled ? '正在生成回答，请稍候…' : '请输入您的问题...'"
      @keydown.enter.exact.prevent="handleSend"
      rows="1"
      ref="textarea"
      :disabled="isDisabled"
    ></textarea>
    <button
      class="send-btn"
      @click="handleSend"
      :disabled="isDisabled || !message.trim()"
      :aria-busy="loading"
      :aria-label="loading ? '发送中' : '发送'"
    >
      <svg v-if="!loading" viewBox="0 0 24 24" width="24" height="24">
        <path
          fill="currentColor"
          d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"
        ></path>
      </svg>
      <span v-else class="spinner" aria-hidden="true"></span>
    </button>
  </div>
</template>

<script>
import { ref, watch, computed } from "vue";

export default {
  props: {
    disabled: {
      type: Boolean,
      default: false,
    },
    loading: {
      type: Boolean,
      default: false,
    },
  },
  emits: ["send"],
  setup(props, { emit }) {
    const message = ref("");
    const textarea = ref(null);

    const isDisabled = computed(() => props.disabled || props.loading);

    const handleSend = () => {
      if (isDisabled.value) return;
      if (message.value.trim()) {
        emit("send", message.value.trim());
        message.value = "";
      }
    };

    watch(message, () => {
      if (textarea.value) {
        textarea.value.style.height = "auto";
        textarea.value.style.height = `${Math.min(
          textarea.value.scrollHeight,
          150
        )}px`;
      }
    });

    return {
      message,
      textarea,
      handleSend,
      isDisabled,
    };
  },
};
</script>

<style>
.chat-input {
  display: flex;
  align-items: flex-end;
  gap: 0.5rem;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 0.75rem;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
}

.chat-input textarea {
  flex: 1;
  border: none;
  resize: none;
  outline: none;
  font-family: inherit;
  font-size: 1rem;
  max-height: 150px;
  overflow-y: auto;
}

.chat-input textarea::placeholder {
  color: #999;
}

.send-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0.5rem;
  color: #666;
  width: 42px;
  height: 42px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  transition: background-color 0.2s, color 0.2s;
}

.send-btn:hover {
  color: #333;
  background-color: #f5f5f5;
}

.send-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.chat-input.disabled {
  opacity: 0.9;
}

.spinner {
  width: 18px;
  height: 18px;
  border: 2px solid rgba(0, 0, 0, 0.15);
  border-top-color: #666;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
